package com.zwh.config;

import com.zwh.listener.event.SqlEvent;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.executor.statement.StatementHandler;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.plugin.*;
import org.apache.ibatis.session.ResultHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.WebApplicationContext;

import java.lang.reflect.Method;
import java.sql.Statement;
import java.util.Properties;

/**
 * ddl拦截器
 */
@Slf4j
@Intercepts({
        @Signature(
                type = Executor.class,
                method = "update",
                args = {MappedStatement.class, Object.class}
        )
})
@Component
public class SqlInterceptor implements Interceptor {
    @Autowired
    private WebApplicationContext webApplicationContext;


    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        //判断操作类型(insert/update/delete)，找对应的处理器处理
        Method method = invocation.getMethod();
        MappedStatement mappedStatement = (MappedStatement)invocation.getArgs()[0];
        //这里的参数是传递给 SQL 语句的对象，通常是你的实体类或参数的实例。如果你只是想获取 SQL 语句本身而不关心参数的具体值，可以传递 null。
        BoundSql boundSql = mappedStatement.getBoundSql(null);
        String sql = boundSql.getSql();
        SqlEvent sqlEvent = new SqlEvent("object");
        //发布事件
        webApplicationContext.publishEvent(sqlEvent);
        return invocation.proceed();
    }

    @Override
    public Object plugin(Object target) {
        // 生成代理对象（MyBatis提供的工具方法，避免自己写代理逻辑）
        return Plugin.wrap(target, this);
    }

    @Override
    public void setProperties(Properties properties) {

    }
}
